<?php
/*
EasyMeal is a sample PHP+CakePHP+Sqlite meal order program.
Copyright (C) 2008 iworm

This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/

class OrderController extends AppController{
    var $name = 'Order';
    var $uses = array('People', 'Shop', 'Food', 'Order');
    var $helpers = array('javascript');
    var $cookieTime = 63072000;

    function index(){
        $this->getWeather();
        $this->pageTitle = 'EasyMeal订餐网';
        $people = $this->People->find('all', array(
            'order' => 'name'
        ));

        $shops = $this->Shop->findAll();

        $lastShopId = 1;

        if($_COOKIE['cookieShop'] != "")
        {
            $lastShopId = $_COOKIE['cookieShop'];
        }

        $foods = $this->Food->find('all', array(
            'conditions' => array('ShopId' => $lastShopId)
        ));

        $count = array('1', '2', '3', '4', '5');

        $this->set('people', $people);
        $this->set('shops', $shops);
        $this->set('foods', $foods);
        $this->set('count', $count);

        $this->set('cookiePeople', $_COOKIE['cookiePeople']);
        $this->set('cookieShop', $_COOKIE['cookieShop']);
        $this->set('cookieFood', $_COOKIE['cookieFood']);
        $this->set('cookieCount', $_COOKIE['cookieCount']);

        $isLogin = $this->Session->read('islogin');

        if(!$isLogin)
        {
            $isLogin = 0;
        }

        $this->set('isLogin', $isLogin);
        $this->set('type', 'people');

        $this->sendInvitationMail($people);
    }

    function isNeedSendMail(){
        date_default_timezone_set('Asia/Shanghai');
        $today = date('Y,m,d');
        $day = file_get_contents(ROOT . '/config/day.txt');

        if($today != $day){
            $fp=fopen(ROOT . '/config/day.txt','w');
            fwrite($fp,$today);
            fclose($fp);

            return true;
        }
        else{
            return false;
        }
    }

    function isNeedGetWeather(){
        date_default_timezone_set('Asia/Shanghai');
        $today = date('Y,m,d');
        $day = file_get_contents(ROOT . '/config/weatherday.txt');

        if($today != $day){
            $fp=fopen(ROOT . '/config/weatherday.txt','w');
            fwrite($fp,$today);
            fclose($fp);

            return true;
        }
        else{
            return false;
        }
    }

    function sendInvitationMail($people){
        $isNeedSendMail = $this->isNeedSendMail();       

        if($isNeedSendMail)
        {
            include_once('components/class.phpmailer.php');

            $mail = new PHPMailer();

            foreach($people as $onepeople)
            {
                $mail->AddAddress($onepeople['People']['email'], $onepeople['People']['name']);
            }
            
            $mail->AddAddress("wormreg@gmail.com", "Roger Li");
            //$mail->AddAddress("rogerli@cdcsoftware.com", "Roger Li");
            
            $mail->CharSet    = "utf-8";
            $mail->Subject    = "今天订餐了吗?";

            $body             = $mail->getFile(ROOT . DS . 'app' . DS . 'controllers' . DS . 'components' . DS . 'mail' . DS . 'invitationmail.html');
            //$body             = eregi_replace("[\]",'',$body);

            $mail->From       = "rogerli@cdcsoftware.com";
            $mail->FromName   = "Easy Meal";

            $mail->MsgHTML($body);

            //$mail->AddAttachment("images/phpmailer.gif");             //attachment

            $mail->Send();
        }
    }

    function view()
    {

    }
    

    function getOrders(){
        $this->getWeather();
        $this->pageTitle = '查看订餐历史 － EasyMeal订餐网';

        if($this->params['url']['type'] == 'all')
        {
            $orders = $this->Order->findAll();
        }
        elseif($this->params['url']['type'] == 'today')
        {
            $orders = $this->Order->find('all', array(
                'conditions' => array('created >=' => date('Y-m-d', strtotime('now')))
            ));
        }
        else
        {
            $peopleId = $this->params['url']['peopleId'];
            $orders = $this->Order->find('all', array(
                'conditions' => array(
                    'peopleId' => $peopleId,
                    'paid' => '0'
                )
            ));
        }

        $this->set('orders', $orders);

        $isLogin = $this->Session->read('islogin');

        if(!$isLogin)
        {
            $isLogin = 0;
        }

        $this->set('isLogin', $isLogin);
        $this->set('type', $this->params['url']['type']);

        $this->layout = 'ajax';
        exit(0);
    }

    function canOrderThisShop($shopId){
        date_default_timezone_set('Asia/Shanghai');
        $orders = $this->Order->find('all', array(
                'conditions' => array('created >=' => date('Y-m-d', strtotime('now')))
            ));

        if(count($orders) > 0 && $orders[0]['Order']['shopId'] != $shopId){
            return $orders[0]['Shop']['name'];
        }
        else{
            return '';
        }
    }

    function add(){
        $this->getWeather();
        $this->pageTitle = '预定 - EasyMeal订餐网';

        date_default_timezone_set('Asia/Shanghai');

        $isLogin = $this->Session->read('islogin');

        if(!$isLogin)
        {
            $isLogin = 0;
        }

        $this->set('isLogin', $isLogin);

        $message = $this->canOrderThisShop($this->params['form']['shopId']);

        if(!$isLogin && date('H:i', time()) > '10:00'){
            $this->set('message', '已经超过10点了, 请到订餐管理员那里确认是否还可以订餐.');
            $this->render('error');
            return;
        }
        
        if($message != ''){
            $this->set('message', '今天只能在 ' . $message . ' 订餐.');
            $this->render('error');
            return;
        }

        $people = $this->People->findById($this->params['form']['peopleId']);
        $shop = $this->Shop->find('all', array(
                        'conditions' => array(
                                'id' => $this->params['form']['shopId']
                            ),
                        'recursive' => 0
                    ));

        if(count($shop) != 1){
            $this->set('message', '请选择正确的餐馆.');
            $this->render('error');
            return;
        }

        $food = $this->Food->find('all', array(
                'conditions' => array(
                    'Food.shopid' => $this->params['form']['shopId'],
                    'Food.id' => $this->params['form']['foodId']
                ),
                'recursive' => 0
            )
        );

        if(count($food) != 1){
            $this->set('message', '请选择正确的食物.');
            $this->render('error');
            return;
        }

        $count = $this->params['form']['count'];

        $myorder = array(
            'peopleId' => $people['People']['id'],
            'foodId' => $food[0]['Food']['id'],
            'shopId' => $shop[0]['Shop']['id'],
            'count' => $count
        );

        $this->Order->save($myorder);

        setcookie("cookiePeople", $people['People']['id'], time() + $cookieTime);
        setcookie("cookieShop", $shop['Shop']['id'], time() + $cookieTime);
        setcookie("cookieFood", $food['Food']['id'], time() + $cookieTime);
        setcookie("cookieCount", $count, time() + $cookieTime);

        echo $HTTP_COOKIE_VARS['cookiePeople'];

        $this->set(array(
            'people' => $people['People']['name'], 
            'shop' => $shop[0]['Shop']['name'],
            'food' => $food[0]['Food']['name'], 
            'price' => $food[0]['Food']['price'],
            'count' => $count
        ));
    }

    function pay(){
        $this->pageTitle = '付款 - EasyMeal订餐网';

        if(!$this->Session->read('islogin'))
        {
            $this->redirect('/admin');
            exit(0);
        }

        date_default_timezone_set('Asia/Shanghai');
        $this->Order->id = $this->params['url']['orderId'];
        $this->Order->saveField('paid', '1');

        $this->redirect('/order/view/?type=' . $this->params['url']['type']);
        exit(0);
    }

    function getFoodsByShop(){
        $shopId = $this->params['url']['shopId'];
        $shop = $this->Shop->findById($shopId);

        $this->set('foods', $shop);
        $this->layout = 'ajax';
    }

    function delete(){
        $this->pageTitle = '删除订单 - EasyMeal订餐网';

        if(!$this->Session->read('islogin'))
        {
            $this->redirect('/admin');
            exit(0);
        }

        date_default_timezone_set('Asia/Shanghai');
        $this->Order->del($this->params['url']['orderId'], false);

        $this->redirect('/order/view/?type=' . $this->params['url']['type']);
        exit(0);
    }

    function getWeather(){
        $weather = '';
        $xmlString = '';
        if($this->isNeedGetWeather())
        {
            include_once('components/HttpClient.class.php');
        
            $client = new HttpClient('www.accuweather.com');
            if (!$client->get('/adcbin/forecastfox/weather_data.asp?location=ASI|CN|CH024|SHANGHAI|&metric=1&partner=forecastfox')) {
                $weather = '天气变化莫测';
            } else {
                $xmlString = $client->getContent();

                $fp=fopen(ROOT . '/config/weather.txt','w');
                fwrite($fp, $xmlString);
                fclose($fp);
            }
        }
        else
        {
            $xmlString = file_get_contents(ROOT . '/config/weather.txt');
        }

        $xmlDOM = new SimpleXMLElement($xmlString);

        $weather = $xmlDOM->forecast->day[0]->daytime->txtshort . ', 最高' . $xmlDOM->forecast->day[0]->daytime->hightemperature . '度';

        $this->set('weather', $weather);
    }
}
?>
